import axios from 'axios';
import { useUserStore } from '@/stores/user';

const service = axios.create({
    baseURL: "http://localhost:8080", 
    timeout: 5000
});

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const userStore = useUserStore();
        if (userStore.token) {
            config.headers['Authorization'] = 'Bearer ' + userStore.token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        if (error.response && error.response.status === 401) {
            // token过期或无效，跳转到登录页
            const userStore = useUserStore();
            userStore.logout();
            window.location.href = '/login';
        }
        return Promise.reject(error);
    }
);

export default service;